import { Service } from 'egg';
import * as Excel from 'exceljs';
import * as blue from 'bluebird';


const DB_ACCOUNT_PRODUCT = 'platform_account_product';
const DB_USER = 'platform_user';
const DB_APP_NOTE = 'app_note';
const DB_CUSTOMER = '_customer';
const DB_HISTORY = '_history';
const DB_Call = '_c5_call_sheet';

export default class exportAppNoteService extends Service {
  
  public async exportNote() {
    const {ctx} = this;
    const body = ctx.request.body;
    const {startTime, endTime, accountId} = body;
    const doc = await this.app.commonDB.db('bill').collection(DB_ACCOUNT_PRODUCT)
      .findOne({_id: `${accountId}_cc`}, {fields: {_id: 1, dataDB:1, account:1}});
    const dataDB = doc.dataDB;
    this.logger.info('datadbv: ', dataDB);

    const agentNameMap = {};
    const agentList = await this.app.commonDB.db('bill').collection(DB_USER).find({account: accountId }, {fields: {displayName: 1, exten: 1}});
    agentList.forEach((e) => {
      agentNameMap[e._id] = `${e.displayName}-${e.exten}`
    });
    const condition = {
      accountId,
      createTime: {
        $gte: startTime,
        $lt: endTime,
      }
    }
    /**
     * {
      "_id": "6b7c3670-264a-11eb-888f-4f68efe2ad23",
      "accountId": "T00000003380",
      "userId": "15e48070-c0bd-11ea-aa69-510bad66a2b7",
      "executor": "15e48070-c0bd-11ea-aa69-510bad66a2b7",
      "remark": "2011141517465096230XXXX552支付房费",
      "notifyTime": "2020-11-16 10:00",
      "customerId": "51a2ce80-107e-11eb-a248-2d80df4b22bf",
      "createTime": "2020-11-14 15:24:23",
      "lastUpdateTime": "2020-11-14 15:24:23",
      "status": "0",
      "deal": "1"
    }
     */
    const appNoteList = await this.app.commonDB.db('cc').collection(DB_APP_NOTE).find(condition).toArray();
    const count = await this.app.commonDB.db('cc').collection(DB_APP_NOTE).count(condition);
    this.logger.info(`本次找到联系计划：${count}条`);
    
    const customerIds: any[] = appNoteList.map((e) => {
      return e.customerId;
    });
    const customerList = await this.app.commonDB.db(dataDB).collection(`${accountId}${DB_CUSTOMER}`).find({_id: {$in: customerIds}}, {fields: {
      name: 1,
    }}).toArray();
    const customerMap = {};
    customerList.forEach((e) => {
      customerMap[e._id] = e.name;
    });

    const filename = `./logs/app_note_${accountId}-${startTime}-${endTime}-${Date.now()}.xlsx`;
    const options = {
      filename,
      useStyles: true,
      useSharedStrings: true
    };
    const workbook = new Excel.stream.xlsx.WorkbookWriter(options);
    // const workbook = new Excel.Workbook(options);

    // sheet1
    const sheet = workbook.addWorksheet('联系计划列表');
    sheet.columns = [
      { key: '_id', header: 'id' } as any,
      { key: 'accountId', header: '账号' } as any,
      { key: 'customerId', header: '客户id' } as any,
      { key: 'customerName', header: '客户名' } as any,
      { key: 'userName', header: '创建人' } as any,
      { key: 'executeName', header: '执行人' } as any,
      { key: 'createTime', header: '创建时间' } as any,
      { key: 'status', header: '是否完成' } as any,
      { key: 'notifyTime', header: '提醒时间' } as any,
      { key: 'remark', header: '联系内容' } as any,
    ] as any;
    appNoteList.forEach((note) => {
      note.customerName = customerMap[note.customerId];
      note.userName = agentNameMap[note.userId] || note.userId;
      note.executeName = note.executor ? agentNameMap[note.executor] : note.userName;
      note.status = note.status === '0' ? '未完成' : '已完成';
      sheet.addRow(note).commit();
    });
    sheet.commit();
    // 联系历史列表
    const sheet2 = workbook.addWorksheet('联系历史列表');
    sheet2.columns = [
      { key: 'customer', header: '客户id' } as any,
      { key: 'customerName', header: '客户名' } as any,
      { key: 'typeName', header: '类型' } as any,
      { key: 'businessNumber', header: '工单号' } as any,
      { key: 'businessCreateUser', header: '工单创建人' } as any,
      { key: 'createTime', header: '时间' } as any,
      { key: 'dispose', header: '处理状态' } as any,
      { key: 'platform', header: '在线处理平台' } as any,
      { key: 'chatId', header: '会话id' } as any,
      { key: 'sid', header: '会话名' } as any,
      { key: 'callId', header: '通话编号' } as any,
      { key: 'callNumber', header: '主叫' } as any,
      { key: 'calledNumber', header: '被叫' } as any,
      
    ] as any;
    const query = {
      createTime: {
        $gte: startTime,
        $lt: endTime,
      },
      customer: '',
      type: {$in: ['business', 'chat', 'callin', 'callout']}
    }
    await blue.mapSeries(customerIds, async (customerId) => {
      query.customer = customerId;
      const name = customerMap[customerId];
      this.logger.info('处理客户', customerId, name);
      // sheet2.addRow({
      //   customer: customerId,
      //   customerName: name,
      // }).commit();
      const histories = await this.app.commonDB.db(dataDB).collection(`${accountId}${DB_HISTORY}`).find(query).toArray();
      if (histories.length > 0) {
        await blue.mapSeries(histories, async (e) => {
          if (e.type === 'business') {
            /**
               * {
              "_id" : "3978f1d0-a848-11e9-ad30-e784b197e9fd",
              "type" : "business",
              "customer" : "c0f64120-97f0-11e9-824d-39af3fe9da76",
              "createTime" : "2019-07-17 12:06:16",
              "businessType" : "65bdc990-a844-11e9-8dc3-0dfe00b5b577",
              "agent" : "764f1830-97c4-11e9-824d-39af3fe9da76",
              "status" : "65be3ec0-a844-11e9-8dc3-0dfe00b5b577",
              "lastUpdateTime" : "2019-07-17 14:37:17",
              "biUpdateTime" : "2019-07-17 12:06:16",
              "comments" : "",
              "beginTime" : 1563336376758,
              "endTime" : 1563345437658,
              "dispose" : "complete",
              "master" : "702cb580-97af-11e9-ab21-6717859e3a45",
              "number" : "2019071700001"
              }
             */
            e.typeName = '工单';
            e.customerName = customerMap[e.customer] || '';
            e.businessNumber = e.number;
            e.businessCreateUser = agentNameMap[e.agent] || e.agent;
            e.createTime = e.createTime;
            e.dispose = e.dispose;
            sheet2.addRow(e).commit();
          } else if (e.type === 'chat') {
            e.typeName = '在线';
            e.customerName = customerMap[e.customer] || '';
            e.platform = e.platform;
            e.chatId = e._id;
            e.sid = e.sid;
            e.dispose = e.dispose;
            sheet2.addRow(e).commit();
          } else if (e.type === 'callin') {
            e.typeName = '普通呼入';
            e.customerName = customerMap[e.customer] || '';
            e.callId = e._id;
            const calldoc: any = await this.getCallDoc(dataDB, e._id, accountId);
            e.callNumber = calldoc.CALLED_NO;
            e.calledNumber = calldoc.CALL_NO;
            sheet2.addRow(e).commit();;
          } else if (e.type === 'callout') {
            e.typeName = '普通外呼';
            e.customerName = customerMap[e.customer] || '';
            e.callId = e._id;
            // e.callNumber = e.recordFile ? e.recordFile.split('_')[3] : '';
            const calldoc: any = await this.getCallDoc(dataDB, e._id, accountId);
            e.callNumber = calldoc.CALL_NO;
            e.calledNumber = calldoc.CALLED_NO;
            sheet2.addRow(e).commit();;
          }
        })

      }
    })

    await workbook.commit();
    this.logger.info('导出完成');
    ctx.sendSuccess();
  }

  private async getCallDoc(dataDB: string, callId: string, accountId: string) {
    const callDoc = await this.app.commonDB.db(dataDB).collection(`${accountId}${DB_Call}`).findOne({_id: callId});
    return callDoc;

  }
}